﻿using SeeSharpTools.JY.GUI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using thinger.DataConvertLib;
using xiaoxiong.KYJDAL.Services;
using xiaoxiong.ScadaProModbusRtu.childFrm;
using xiaoxiong.ScadaProModbusRtu.Common;
using xiaoxiong.ScadaProModbusRtu.Message.MessageForms;

namespace xiaoxiong.ScadaProModbusRtu
{
    public partial class FrmHistoryTrend : Form
    {
        public ActualDataService ActualDataService = new ActualDataService();
        public FrmHistoryTrend()
        {
            InitializeComponent();



            //设置x轴数据类型
            this.chart_HistoryTrend.XDataType = StripChartX.XAxisDataType.TimeStamp;
            chart_HistoryTrend.TimeStampFormat = "HH:mm:ss";

            //设置图例
            this.chart_HistoryTrend.LegendVisible = false;

            //设置数据点
            this.chart_HistoryTrend.DisplayPoints = 100000;

            //Y1 范围
            this.chart_HistoryTrend.AxisY.Minimum = -10.0f;
            this.chart_HistoryTrend.AxisY.Maximum = 50.0f;
            this.chart_HistoryTrend.AxisY.AutoScale = false;
            //Y2 范围
            this.chart_HistoryTrend.AxisY2.Minimum = 0.0f;
            this.chart_HistoryTrend.AxisY2.Maximum = 1.0f;
            this.chart_HistoryTrend.AxisY2.AutoScale = false;



            //设置一下初始时间
            this.dtp_StartTime.Value = DateTime.Now.AddHours(-2.0);
            this.dtp_EndTime.Value = DateTime.Now;


            if (CommonMethods.plcDevice != null && CommonMethods.sysConfig != null)
            {
                //初始化selectParam
                for (int i = 0; i < Math.Min(CommonMethods.sysConfig.ShowSeriesCount,
                    CommonMethods.plcDevice.StoreVarList.Count); i++)
                {
                    selectParam.Add(CommonMethods.plcDevice.StoreVarList[i].Comments);
                }
                BindComBox();
            }
        }

        private void BindComBox()
        {
            this.comboBox1.SelectedIndexChanged -= ComboBox1_SelectedIndexChanged;

            this.comboBox1.DataSource = selectParam;

            this.comboBox1.SelectedIndexChanged += ComboBox1_SelectedIndexChanged;
        }

        private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < this.chart_HistoryTrend.SeriesCount; i++)
            {
                this.chart_HistoryTrend.Series[i].Visible = this.chart_HistoryTrend.Series[i].Name == this.comboBox1.Text;
            }
        }

        //查询方法
        //创建查询参数集合
        private List<string> selectParam = new List<string>();
        private void btn_Find_Click(object sender, EventArgs e)
        {
            string start = this.dtp_StartTime.Text;
            string end = this.dtp_EndTime.Text;

            Task<OperateResult<DataTable>> task = Task.Run(() =>
            {
                return QueryProcess(start, end);
            });

            var result = task.GetAwaiter().GetResult();

            if (result.IsSuccess)
            {
                //显示
                UpdateChart(result.Content,Convert.ToDateTime(start),Convert.ToDateTime(end));
            }
            else
            {
                new FrmMessageBoxWithoutAck("查询出错 " + result.Message,"查询出错").ShowDialog();
            }
        }

        private OperateResult<DataTable> QueryProcess(string start, string end)
        {
            if (selectParam.Count == 0)
            {
                return OperateResult.CreateFailResult<DataTable>("至少选择一个参数");
            }

            DateTime startTime = Convert.ToDateTime(start);
            DateTime endTime = Convert.ToDateTime(end);

            if (startTime > endTime)
            {
                return OperateResult.CreateFailResult<DataTable>("开始时间不能大于结束时间");
            }

            TimeSpan timeSpan = endTime - startTime;

            if(timeSpan.TotalHours > 24.0)
            {
                return OperateResult.CreateFailResult<DataTable>("不能查过24小时");
            }

            //查询参数集合
            var columns = selectParam.Select( c => CommonMethods.plcDevice.StoreVarList
            .FirstOrDefault(d => d.Comments == c).VarName).ToList();

            DataTable dataTable = ActualDataService.QueryActualDataByTime(start, end, columns);

            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                return OperateResult.CreateSuccessResult<DataTable>(dataTable);
            }
            else
            {
                return OperateResult.CreateFailResult<DataTable>("该段时间没有数据");
            }
        }


        /// <summary>
        /// 更新过程
        /// </summary>
        /// <param name="dataTable"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        private void UpdateChart(DataTable dataTable,DateTime start, DateTime end)
        {
            //清除chart
            this.chart_HistoryTrend.Clear();

            //获取曲线数量
            int count = selectParam.Count;

            this.chart_HistoryTrend.SeriesCount = count;

            for (int i = 0; i < count; i++)
            {
                this.chart_HistoryTrend.Series[i].Name = selectParam[i];
                this.chart_HistoryTrend.Series[i].Width = StripChartXSeries.LineWidth.Middle;

                this.chart_HistoryTrend.Series[i].Visible = true;

                if (selectParam[i].Contains("温度"))
                {
                    this.chart_HistoryTrend.Series[i].YPlotAxis = StripChartXAxis.PlotAxis.Primary;
                }
                else
                {
                    this.chart_HistoryTrend.Series[i].YPlotAxis = StripChartXAxis.PlotAxis.Secondary;
                }
            }

            //数据绑定
            DateTime[] XData = GetDateTimesList(start, end).ToArray();

            double[,] YData = new double[count,XData.Length];

            var valueList = GetDicValueFromDataTable(dataTable);

            for (int i = 0;i < XData.Length;i++)
            {
                if (valueList.ContainsKey(XData[i]))
                {
                    for (int j = 0;j < count;j++)
                    {
                        try
                        {
                            YData[j, i] = Convert.ToDouble(valueList[XData[i]][j]);
                        }
                        catch
                        {
                            YData[j, i] = 0;
                        }
                       
                    }
                }
                else
                {
                    for(int j = 0; j < count; j++)
                    {
                        YData[j, i] = 0;
                    }
                }
            }

            this.chart_HistoryTrend.Plot(YData,XData);
        }


        /// <summary>
        /// 获取开始时间和结束时间之间的所有时间点集合
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        private List<DateTime> GetDateTimesList(DateTime start,DateTime end)
        {
            List<DateTime> timeList = new List<DateTime>();

            DateTime t1 = start;

            while (t1 < end)
            {
                timeList.Add(t1);
                t1 = t1.AddSeconds(1);
            }

            return timeList;
        }


        private Dictionary<DateTime,List<string>> GetDicValueFromDataTable(DataTable dataTable)
        {
            Dictionary<DateTime, List<string>> valueList = new Dictionary<DateTime, List<string>>();
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                DateTime dateTime = Convert.ToDateTime(dataTable.Rows[i][0]);

                List<string> temp = new List<string>();
                for (int j = 0; j < dataTable.Columns.Count - 1; j++)
                {
                    temp.Add(dataTable.Rows[i][j + 1].ToString());
                }
                if (!valueList.ContainsKey(dateTime))
                {
                    valueList.Add(dateTime, temp);
                }
            }
            return valueList;
        }

        private void btn_Save_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "图片文件(*.jpg)|*.jpg|所有文件|*.*";
            saveFileDialog.FileName = "历史趋势保存图片" + DateTime.Now.ToString("yyyyMMddHHmmss");
            saveFileDialog.DefaultExt = "jpg";
            saveFileDialog.AddExtension = true;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                this.chart_HistoryTrend.SaveAsImage(saveFileDialog.FileName);
                Process.Start(saveFileDialog.FileName);
            }
        }

        private void btn_Export_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "图片文件(*.csv)|*.csv|所有文件|*.*";
            saveFileDialog.FileName = "历史趋势保存csv" + DateTime.Now.ToString("yyyyMMddHHmmss");
            saveFileDialog.DefaultExt = "csv";
            saveFileDialog.AddExtension = true;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                this.chart_HistoryTrend.SaveAsImage(saveFileDialog.FileName);
                Process.Start(saveFileDialog.FileName);
            }
        }

        private void btn_Select_Click(object sender, EventArgs e)
        {
            FrmParamSel frmParamSel = new FrmParamSel(this.selectParam);
            
            if(frmParamSel.ShowDialog() == DialogResult.OK)
            {
                this.selectParam = frmParamSel.selectParamList;

                BindComBox();
            }
        }
    }
}
